import { DownOutlined, DeleteOutlined, SearchOutlined, EditOutlined } from '@ant-design/icons';
import {
  Layout,
  Button,
  Input,
  Space,
  Typography,
  Dropdown,
  MenuProps,
  message,
  Modal,
  Drawer,
  Skeleton,
} from 'antd';
import dayjs from 'dayjs';
import React, { useState, useEffect, lazy } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useContextSelector } from 'use-context-selector';

import datasetService from '@/api/services/datasetService';
import { SvgIcon } from '@/components/icon';
import Back from '@/components/router/Back';
import useInitialize from '@/hooks/event/use-initialize';
import useWindowWidth from '@/hooks/event/use-window-width';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import { useRouter, useParams } from '@/router/hooks';
import { useDatasetStore } from '@/store/datasetStore';
import { useUserInfo } from '@/store/userStore';
import { DatasetEvent } from '@/types/dataset';
import { getNodeParentType } from '@/utils/tree';

import DatasetsTree from './components/DatasetsTree';
import NewDatasetModal from './components/NewDatasetModal';
import DatasetsContextProvider, { DatasetsContext } from './context';
import DatasetDetailTree from './components/dataset-detail-tree/index';
import RouterMenu from '@/pages/components/menus/RouterMenu';
import { useManagePage } from '@/store/configStore';
import { FcsRewareHousingReq } from '@/types/api';
import usePermission from '@/hooks/event/usePermission';

// import DatasetDetail from '@/pages/dataset-detail/index';
// import CollectionDetail from '@/pages/collection-detail/index';

const CollectionDetail = lazy(() => import('@/pages/collection-detail/index'));
const DatasetDetail = lazy(() => import('@/pages/dataset-detail/index'));

import { MAX_NAME_LENGTH, MAX_DOCUMENT_LENGTH } from '@/common';
import { useDatasetsActions } from '@/store/datasetsStore';
import Modals from '@/components/modals/Modals';
const Confirm = Modal;
interface FileData {
  key: string;
  name: string;
  type: string;
  size: string;
  uploader: string;
  uploadDate: string;
  status: 'active' | 'inactive';
}

// TODO : 这个组件逻辑很混乱，有时间的时候重构一下

function DatasetList() {
  const [searchParams] = useSearchParams();
  const id = searchParams.get('id');
  const { homePage } = useInitialize();
  const managePage = useManagePage();

  const router = useRouter();
  const { isPc } = useWindowWidth();
  const { role, groupId } = useUserInfo();
  const { appId = '' } = useParams() as { appId: string };

  const [sidebarItems, setSideBarItems] = useState([]);
  const {
    selectedTreeNode,
    selectedTreeData,
    event$,
    currentEditTreeData,
    loading,
    setLoading,
    setSelectedTreeData,
    setSelectedTreeNode,
    setFullTreeData,
  } = useContextSelector(DatasetsContext, (s) => s);

  const { setDataset } = useDatasetsActions();

  const [data, setData] = useState([]);
  const [dataLoading, setDataLoading] = useState(false);

  const [selectedKey, setSelectedKey] = useState('1');
  const [selectedItem, setSelectedItem] = useState<MenuProps['items']>(sidebarItems?.[0]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const { allDatasets, loadAllDatasets, loadCollections, parentIdstore, getParentId } =
    useDatasetStore();

  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);

  const [renameModalVisible, setRenameModalVisible] = useState<boolean>(false);
  const [datasetModalVisible, setDatasetModalVisible] = useState<boolean>(false);
  const [renameKey, setRenameKey] = useState<string | null>(null);
  const [newName, setNewName] = useState<string>('');

  const [newDatasetName, setNewDatasetName] = useState<string>('');
  const [rewarehousingModalVisible, setRewarehousingModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState<boolean>(false);
  const [editKey, setEditKey] = useState<string | null>(null);
  const [editType, setEditType] = useState<string | null>(null);
  const [settingVisible, setSettingVisible] = useState(false);
  const [createDatasetVisible, setCreateDatasetVisible] = useState(false);
  const [createDatasetFolder, setCreateDatasetFolder] = useState(false);

  const [mobileFileVisible, setMobileFileVisible] = useState(false);

  const [searchValue, setSearchValue] = useState('');
  const [containerHeight, setContainerHeight] = useState(900);
  const [containerWidth, setContainerWidth] = useState(300);

  const [dropdownVisible, setDropdownVisible] = useState(false);
  const { Header, Sider, Content } = Layout;
  const { isAdmin, isPermit } = usePermission();

  const [deleteDatasetModalVisible, setDeleteDatasetModalVisible] = useState(false);

  const [showDatasetDetail, setShowDatasetDetail] = useState(false);
  const [showCollectionDetail, setShowCollectionDetail] = useState(false);
  const [datasetDetailParams, setDatasetDetailParams] = useState({
    id: '',
    name: '',
    parentId: '',
  });
  const [collectionDetailParams, setCollectionDetailParams] = useState({
    id: '',
    name: '',
  });

  const handleDatasetDeleteConfirm = async () => {
    if (!selectedTreeNode) {
      return;
    }
    const id = editKey;
    const parent = getNodeParentType(selectedTreeNode.parent, 'dataset');
    if (
      (parent && editType == 'folder') ||
      (selectedTreeNode.id != id && selectedTreeNode.type == 'dataset')
    ) {
      await datasetService.deleteDatasetCollection(id);
    } else {
      await datasetService.datasetDelete({
        id: [id],
        reviewStatus: 'drop',
        app_id: selectedTreeNode.appId,
      });
    }
    setEditKey(null);
    setDeleteDatasetModalVisible(false);
    const datas = selectedTreeData.filter((item) => item.id != id);
    setSelectedTreeData(datas);
    if (selectedTreeNode && selectedTreeNode.parent) {
      selectedTreeNode.parent.children = selectedTreeNode.parent.children?.filter(
        (item) => item.id !== id,
      );
    }
    if (selectedTreeNode.id == id) {
      if (datas.length > 0) {
        setSelectedTreeNode(datas[datas.length - 1]);
      } else {
        setSelectedTreeNode(null);
      }
    } else {
      event$?.emit(DatasetEvent.UPDATECOLLECTION);
    }

    loadAllDatasets({
      groupId: '',
      parentId: '',
      page: 1,
      page_size: 10,
      offset: 0,
      searchText: '',
      isPage: true,
      app_id: appId || '67fcd7c1de9ddb56bea37b6c', //必填
    });
    message.success(`${editType == 'dataset' ? '知识库' : '文件夹'}删除成功`);
  };

  const handleDatasetDeleteCancel = () => {
    setDeleteDatasetModalVisible(false);
  };

  const handleDeleteConfirm = async () => {
    if (editKey) {
      // 调用服务删除数据
      await datasetService.deleteDatasetCollection(editKey);
      setDeleteModalVisible(false);
      setEditKey(null);
      message.success('删除成功');
      if (selectedTreeNode) {
        selectedTreeNode.children = selectedTreeNode.children?.filter(
          (item) => item.key !== editKey,
        );
      }
      event$?.emit(DatasetEvent.UPDATECOLLECTION);
      // fetchCollections(selectedItem);
    }
  };

  const handleDeleteCancel = () => {
    setDeleteModalVisible(false);
    setEditKey(null);
  };

  const handleDelete = (key: string, type: string) => {
    if (!isPermit) {
      message.info('权限暂不支持该操作');
      return;
    }
    setEditKey(key);
    setEditType(type);
    switch (type) {
      case 'folder':
      case 'dataset':
        setDeleteDatasetModalVisible(true);
        break;
      case 'file':
        setDeleteModalVisible(true);
        break;
      default:
        break;
    }
  };

  const handleCreate = (type: string) => {
    if (!isPermit) {
      message.info('权限暂不支持该操作');
      return;
    }

    setEditType(type);

    setCreateDatasetVisible(true);
  };

  const handleRename = (item) => {
    if (!isPermit) {
      message.info('权限暂不支持该操作');
      return;
    }
    setRenameKey(item.key);
    setNewName(item.name);
    setRenameModalVisible(true);
  };

  const handleRenameConfirm = async () => {
    if (!newName) {
      message.error('文档名称不能为空');
      return;
    }
    if (newName.length > MAX_DOCUMENT_LENGTH) {
      message.error(`文档名称长度不能超过 ${MAX_DOCUMENT_LENGTH} 字符`);
      return;
    }
    if (renameKey) {
      const renameData = data.filter((item) => item.key === renameKey)[0];

      // 调用服务更新数据
      await datasetService.updateDatasetCollection({
        id: renameData.id,
        name: newName, // 假设 newName 是新的名称
      });

      // 更新数据源
      const updatedData = data.map((item) => {
        if (item.key === renameKey) {
          return { ...item, name: newName };
        }
        return item;
      });

      // 更新状态
      setData(updatedData);

      // 关闭重命名确认模态框
      setRenameModalVisible(false);
      setRenameKey(null);

      // 显示消息
      message.success('重命名成功');
    }
  };

  const handleRenameCancel = () => {
    setRenameModalVisible(false);
    setRenameKey(null);
  };

  const convertToListItem = (data) => {
    return data.map((item, index) => ({
      key: item._id,
      icon: <SvgIcon icon="ic_rj_book" size={40} />,
      // icon: <SlackOutlined />,
      label: item.name,
      id: item._id,
      type: item.type,
    }));
  };

  const transformFileData = (data: FileData[]) => {
    return data.map((item, index) => {
      const fileType = item.name.split('.').pop() || 'unknown';

      return {
        key: (index + 1).toString(),
        name: item.name,
        type: fileType,
        id: item._id,
        uploadDate: dayjs(item?.createTime).format('YYYY-MM-DD HH:mm:ss'),
        status: item.forbid ? 'inactive' : 'active',
      };
    });
  };

  const loadDatasets = async () => {
    try {
      setLoading(true);
      await loadAllDatasets({
        groupId: '',
        parentId: '',
        page: 1,
        page_size: 10,
        offset: 0,
        searchText: '',
        isPage: true,
        app_id: appId || '67fcd7c1de9ddb56bea37b6c', //必填
      });
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setContainerHeight(window.innerHeight - 20);
    setContainerWidth(window.innerWidth - 130);
    // 获取知识库
    // loadDatasets();
    getParentId(''); //首次清空掉
  }, []);

  const fetchCollections = async (item) => {
    if (item?.id) {
      setDataLoading(true);
      try {
        const resp = await loadCollections({
          datasetId: item?.id ? item.id : '',
          searchText: searchValue,
          pageNum: page,
          pageSize,
        });
        setTotal(resp.total);
        setData(transformFileData(resp?.data));
      } catch (error) {
      } finally {
        setDataLoading(false);
      }
    }
  };

  const fetchDatasets = async (item) => {
    if (item?.id) {
      setDataLoading(true);
      try {
        // const resp = await loadAllDatasets({
        //   parentId: item.id
        // })

        const resp = await datasetService.datasetList({ parentId: item.id });
        console.log(resp);
        const dataset = convertToListItem(resp);
        // console.log(dataset)
        console.log(sidebarItems);

        const updatedSidebarItems = sidebarItems.map((sidebarItem) => {
          if (sidebarItem.id === item.id) {
            return {
              ...sidebarItem,
              children: dataset,
            };
          }
          return sidebarItem;
        });

        // 更新 sidebarItems
        setSideBarItems(updatedSidebarItems);

        console.log(resp);
      } catch (error) {
      } finally {
        setDataLoading(false);
      }
    }
  };

  useEffect(() => {
    clearRowSelection();
  }, [page]);

  const items: MenuProps['items'] = [
    {
      key: '1',
      label: '启用',
    },
    {
      key: '2',
      label: '停用',
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[], selectedRows: FileData[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
  };

  const clearRowSelection = () => {
    setSelectedRowKeys([]);
  };

  const [deleteBatchModalVisible, setDeleteBatchModalVisible] = useState(false);

  const handleBatchDeleteCancel = () => {
    setDeleteBatchModalVisible(false);
  };

  const handleBatchDeleteClick = async () => {
    const selectData = data.filter((item) => {
      return selectedRowKeys.includes(item.key);
    });
    // selectData.map((item) => {
    //   datasetService.deleteDatasetCollection(item.id);
    // });
    await Promise.all(selectData.map((item) => datasetService.deleteDatasetCollection(item.id)));
    const updatedData = data.filter((item) => !selectedRowKeys.includes(item.key));
    setData(updatedData);
    setSelectedRowKeys([]);
    setDeleteBatchModalVisible(false);
    message.success('删除成功');
    // fetchCollections(selectedItem);
  };

  const handeleDatasetSelect = (item) => {
    !isPc && setMobileFileVisible(true);
    setSelectedRowKeys([]);
    setSearchValue('');
    setPage(1);

    if (item.type == 'folder') {
      fetchDatasets(item);
    } else {
      fetchCollections(item);
    }

    setSelectedKey(item.key);
    setSelectedItem(item);

    // 更新url不重载页面
    if (item?.id) {
      const rootUrl = window.location.origin;
      const newUrl = `${rootUrl}/datasets/list?id=${item?.id}`;
      window.history.pushState({}, '', newUrl);
    }
  };

  const datasetRename = () => {
    const name = currentEditTreeData?.type == 'folder' ? '文件夹' : '知识库';
    const newName = newDatasetName.trim();

    if (!newName) {
      message.error(`${name}名称不能为空`);
      return;
    }
    if (newName.length > MAX_DOCUMENT_LENGTH) {
      message.error(`${name}名称长度不能超过 ${MAX_DOCUMENT_LENGTH} 字符`);
      return;
    }
    if (!currentEditTreeData) {
      return;
    }
    const id = currentEditTreeData?.id || currentEditTreeData?._id;
    const parent = getNodeParentType(currentEditTreeData.parent, 'dataset');
    if (currentEditTreeData.reviewStatus === 'reject') {
      message.error(`该${name}已被驳回，无法修改`);
      return;
    }
    // console.log(parent);
    // return
    if (parent) {
      datasetService.updateDatasetCollection({
        id,
        name: newName,
      });
    } else {
      datasetService.updateDatasetFile({
        id: currentEditTreeData._id,
        name: newName,
      });
    }

    currentEditTreeData.name = newName;
    currentEditTreeData.title = newName;
    setDatasetModalVisible(false);
    setNewDatasetName('');
    event$?.emit(DatasetEvent.UPDATEDATASETTREE);
  };

  const datasetCreate = async (datasetName: string) => {
    try {
      setLoading(true);
      setCreateDatasetFolder(true);
      const name = editType == 'dataset' ? '知识库' : '文件夹';
      if (!datasetName) {
        message.error(`${name}名称不能为空！`);
        return;
      }
      if (datasetName.length > MAX_NAME_LENGTH) {
        message.error(`${name}名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
        return;
      }
      const parentId = selectedTreeNode?.id;
      const parentDataset = getNodeParentType(selectedTreeNode?.parent, 'dataset');
      if (editType == 'dataset') {
        await datasetService.createKnowledgeBase({
          type: 'dataset',
          avatar: '/imgs/dataset/dataset.svg',
          name: datasetName,
          intro: '',
          vectorModel: 'embedding-model',
          agentModel: 'vllm-chat-model',
          parentId,
          app_id: appId, //必填
        });
      } else if (editType == 'folder' && !parentDataset) {
        await datasetService.createKnowledgeBase({
          name: datasetName,
          intro: '',
          type: 'folder',
          parentId: parentId ?? null,
          app_id: appId, //必填
          avatar: '/imgs/dataset/dataset.svg',
          vectorModel: '',
          agentModel: '',
          openapiUrl: '',
          dataset_tags: [],
          group_id: '',
          assessor: [],
          administrator: [],
        });
      } else if (parentDataset) {
        await datasetService.createDatasetItem({
          datasetId: parentDataset.id,
          name: datasetName,
          type: 'folder',
          parentId: parentId ?? '',
        });
      } else {
        await datasetService.createDatasetItem({
          datasetId: parentId ?? '',
          name: datasetName,
          type: 'folder',
          parentId: '',
        });
      }
      setEditKey('');
      setCreateDatasetVisible(false);
      loadAllDatasets({
        groupId: '',
        parentId: '',
        page: 1,
        page_size: 10,
        offset: 0,
        searchText: '',
        isPage: true,
        app_id: appId || '67fcd7c1de9ddb56bea37b6c', //必填
      });
      event$?.emit(DatasetEvent.UPDATECOLLECTION);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  event$?.useSubscription(async (val) => {
    if (val == DatasetEvent.DATASETTREECLICKED && !isPc) {
      // setMobileFileVisible(true);
    }
    if (val == DatasetEvent.UPDATEDATASETTREE) {
      //修改文件夹和文档
      if (currentEditTreeData.type === 'folder') {
        loadAllDatasets({
          parentId: parentIdstore,
          groupId: '',
          page: 1,
          page_size: 10,
          offset: 0,
          searchText: '',
          isPage: true,
          app_id: appId, //必填
        });
      } else {
        //暂时注释掉
        // await datasetService.getDatasetFileList({
        //   datasetId: parentIdstore,
        //   page: 1,
        //   page_size: 10,
        //   offset: 0,
        //   searchText: '',
        //   app_id: appId,   //必填
        // })
      }
    }
  });

  const confirmRewareHousing = async () => {
    try {
      const data: FcsRewareHousingReq = {
        file_set: [],
      };
      console.log(data, editKey, editType);

      if (editType == 'dataset' || editType == 'folder') {
        data.file_set.push({
          datasetId: editKey ?? '',
        });
      } else if (editType == 'file') {
        data.file_set.push({
          fileId: editKey ?? '',
        });
      }

      if (data) {
        if (data.file_set?.length == 0) {
          message.info('暂不支持重新入库');
        } else {
          await datasetService.postFcsRewareHousing(data);
        }
      }
      setRewarehousingModalVisible(false);
      setEditKey('');
      setEditType('');
    } catch (error) {}
  };

  const handleRewareHousingClicked = (key: string, type: string) => {
    setEditKey(key);
    setEditType(type);
    setRewarehousingModalVisible(true);
  };

  const importData = () => {
    if (!selectedTreeNode) {
      return;
    }
    const { type } = selectedTreeNode;
    const parent = getNodeParentType(selectedTreeNode.parent, 'dataset');
    const datasetid = type == 'dataset' ? selectedTreeNode.id || selectedTreeNode?._id : parent?.id;
    const name = type == 'dataset' ? selectedTreeNode.name : parent?.name;
    setDatasetDetailParams({
      id: datasetid,
      name: name,
      parentId: selectedTreeNode.type === 'folder' ? selectedTreeNode.id : '',
    });
    setShowDatasetDetail(true);
  };

  return (
    <Layout className="h-full " style={{ background: '#EDEFF7' }} >
      <Layout style={{ background: '#FFFFFF', overflow: 'hidden' }}>
        {
          <Sider
            style={{ background: 'transparent', overflow: 'hidden', height: '0px' }}
            width={'0px'}
            className="flex flex-col overflow-hidden"
          >
            <div className="ml-2 flex h-full" style={{ background: 'transparent' }}>
              <DatasetsTree dataLoading={loading} />
            </div>
          </Sider>
        }
        {/* {allDatasets.length == 0 && !dataLoading && <EmptyPage description="暂无数据" />} */}

        {
          <Content
            className=" h-full overflow-hidden rounded-xl"
            style={{
              overflowY: 'auto',
              overflowX: 'hidden',
              // background:
              //   'linear-gradient(180deg, rgba(251, 252, 255, 0.5) 0%, rgba(255, 255, 255, 0.5) 59.81%)',
            }}
          >
            {(() => {
              if (showCollectionDetail) {
                return (
                  <CollectionDetail
                    collectionId={collectionDetailParams.id}
                    name={collectionDetailParams.name}
                    onBack={() => {
                      setCollectionDetailParams((prev) => ({
                        ...prev,
                        type: 'dataset',
                      }));
                      setDataset({ expandKeys: [] });
                      setShowCollectionDetail(false);
                      setShowDatasetDetail(false);
                    }}
                  />
                );
              }

              if (showDatasetDetail) {
                return (
                  <DatasetDetail
                    id={datasetDetailParams.id}
                    name={datasetDetailParams.name}
                    parentId={datasetDetailParams.parentId}
                    onBack={() => {
                      setCollectionDetailParams((prev) => ({
                        ...prev,
                        type: 'dataset',
                      }));
                      setDataset({ expandKeys: [] });
                      setShowCollectionDetail(false);
                      setShowDatasetDetail(false);
                    }}
                  />
                );
              }

              return (
                <DatasetDetailTree
                  onRewareHousingClicked={handleRewareHousingClicked}
                  dataLoading={loading}
                  isPermit={isPermit}
                  isAdmin={isAdmin}
                  onDeleteClicked={handleDelete}
                  onCreateCicked={handleCreate}
                  onRenameClicked={(name) => {
                    setNewDatasetName(name);
                    setDatasetModalVisible(true);
                  }}
                  createDatasetFolder={createDatasetFolder}
                  onShowDatasetDetail={importData}
                  onShowCollectionDetail={(fileId, name) => {
                    setShowDatasetDetail(false);
                    setShowCollectionDetail(true);
                    setCollectionDetailParams({
                      id: fileId,
                      name: name,
                    });
                  }}
                  onFileType={collectionDetailParams}
                />
              );
            })()}

            {/* {showDatasetDetail ? (
              <DatasetDetail
                id={datasetDetailParams.id}
                name={datasetDetailParams.name}
                parentId={datasetDetailParams.parentId}
                onBack={() => {
                  console.log('onBack');
                  setDataset({
                    expandKeys: [],
                  });
                  setShowDatasetDetail(false);
                }}
              />
            ) : (
              <DatasetDetailTree
                onRewareHousingClicked={handleRewareHousingClicked}
                dataLoading={loading}
                isPermit={isPermit}
                isAdmin={isAdmin}
                onDeleteClicked={handleDelete}
                onCreateCicked={handleCreate}
                onRenameClicked={(name) => {
                  setNewDatasetName(name);
                  setDatasetModalVisible(true);
                }}
                createDatasetFolder={createDatasetFolder}
                onShowDatasetDetail={() => {
                  importData();
                }}
              />
            )} */}
          </Content>
        }
      </Layout>
      {/* {allDatasets.length <= 0 && dataLoading && (
        <div className="h-full w-full items-center p-2">
          <Skeleton active paragraph={{ rows: 20 }} />
        </div>
      )} */}
      <Modals
        open={deleteModalVisible}
        onOk={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
        okText="删除"
        width={300}
        closable={false}
        cancelText="取消"
        centered
        okButtonProps={{ danger: true }}
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size="middle">
              <Button onClick={handleDeleteCancel}>取消</Button>
              <Button type="primary" danger onClick={handleDeleteConfirm}>
                删除
              </Button>
            </Space>
          </div>
        }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '50px',
          }}
        >
          <p style={{ textAlign: 'center' }}>确定要删除该数据源吗？</p>
        </div>
      </Modals>
      <Modals
        title={<div style={{ textAlign: 'center', width: '100%' }}>文档重命名</div>}
        open={renameModalVisible}
        onOk={handleRenameConfirm}
        onCancel={handleRenameCancel}
        okText="确定"
        cancelText="取消"
        closable={false}
        width={300}
        centered
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size={36}>
              <Button onClick={handleRenameCancel}>取消</Button>
              <Button type="primary" onClick={handleRenameConfirm}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input value={newName} onChange={(e) => setNewName(e.target.value)} />
        </div>
      </Modals>
      <Modals
        title={
          <div style={{ textAlign: 'center', width: '100%' }}>
            {currentEditTreeData?.type == 'dataset'
              ? '知识库'
              : currentEditTreeData?.type == 'file'
              ? '文档'
              : '文件夹'}
            重命名
          </div>
        }
        open={datasetModalVisible}
        onOk={datasetRename}
        onCancel={() => {
          setDatasetModalVisible(false);
        }}
        okText="确定"
        cancelText="取消"
        closable={false}
        width={300}
        centered
        // footer={
        //   <div style={{ textAlign: 'center' }}>
        //     <Space size={36}>
        //       <Button
        //         onClick={() => {
        //           setDatasetModalVisible(false);
        //         }}
        //       >
        //         取消
        //       </Button>
        //       <Button type="primary" onClick={datasetRename}>
        //         确定
        //       </Button>
        //     </Space>
        //   </div>
        // }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input value={newDatasetName} onChange={(e) => setNewDatasetName(e.target.value)} />
        </div>
      </Modals>

      <NewDatasetModal
        editType={editType ?? ''}
        open={createDatasetVisible}
        onConfirm={datasetCreate}
        onCancel={() => {
          setCreateDatasetVisible(false);
        }}
      />

      <DeleteConfirmModal
        visible={deleteDatasetModalVisible}
        text="确定要删除吗？"
        onCancel={handleDatasetDeleteCancel}
        onConfirm={handleDatasetDeleteConfirm}
      />

      <DeleteConfirmModal
        visible={deleteBatchModalVisible}
        text="确定要删除该数据源吗？"
        onCancel={handleBatchDeleteCancel}
        onConfirm={handleBatchDeleteClick}
      />
      <Confirm
        open={rewarehousingModalVisible}
        title="确认需要重新导入？"
        onOk={confirmRewareHousing}
        onCancel={() => {
          setRewarehousingModalVisible(false);
        }}
      />

      {/* <PermissionDrawer visible={settingVisible} onClose={() => setSettingVisible(false)} /> */}

      <Drawer
        title={
          <span
            style={{
              fontSize: '20px',
              fontWeight: 500,
              color: '#474C5F',
            }}
          >
            文件列表
          </span>
        }
        open={mobileFileVisible}
        onClose={() => {
          setMobileFileVisible(false);
        }}
        width="100%"
        zIndex={100}
        closeIcon={<SvgIcon icon="ic-back" size={24} />}
        // className="custom-drawer-header flex justify-between pt-2"
        style={{ padding: 0 }}
        className="drawer"
      >
        <div className="mt-2">
          <DatasetDetailTree
            dataLoading={dataLoading}
            onRewareHousingClicked={handleRewareHousingClicked}
            onDeleteClicked={handleDelete}
            onCreateCicked={handleCreate}
            onCloseCicked={() => {
              setMobileFileVisible(false);
            }}
            onRenameClicked={(name) => {
              setNewDatasetName(name);
              setDatasetModalVisible(true);
            }}
            onFileType={collectionDetailParams}
          />
        </div>
      </Drawer>
    </Layout>
  );
}

function RenderDatasets() {
  return (
    <DatasetsContextProvider>
      <DatasetList />
      {/* <VideoPlayer src={srsStreamUrl} /> */}
    </DatasetsContextProvider>
  );
}

export default RenderDatasets;
